package xyz.chaobei.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import xyz.chaobei.entity.OrgRolePermissionEntity;
import xyz.chaobei.entity.ro.OrgRolePermissionAO;
import xyz.chaobei.service.OrgRolePermissionService;
import xyz.chaobei.util.JsonUtil;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("api/orgRolePermission")
@Valid
public class OrgRolePermissionController {

    @Autowired
    private OrgRolePermissionService orgRolePermissionService;

    @GetMapping("/{id}")
    public JSONObject getByRoleId(@PathVariable("id") @Valid @NotNull Integer id) {

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("role_id_", id);
        List<OrgRolePermissionEntity> rolePermissionEntities = orgRolePermissionService.list(queryWrapper);

        List<Integer> ids = rolePermissionEntities.stream().map(item -> item.getPerId()).collect(Collectors.toList());
        return JsonUtil.getSuccess(ids);
    }

    /**
     * 添加权限信息
     *
     * @param ao
     * @return
     */
    @PostMapping("/")
    public JSONObject save(@RequestBody @Valid OrgRolePermissionAO ao) {

        UpdateWrapper wrapper = new UpdateWrapper();
        wrapper.eq("role_id_", ao.getRoleId());

        /**
         * 删除原有的权限
         */
        boolean isDel = orgRolePermissionService.remove(wrapper);

        List<OrgRolePermissionEntity> saveEntity = new LinkedList<>();

        ao.getPermissions().stream().forEach(item -> {
            OrgRolePermissionEntity entity = new OrgRolePermissionEntity();
            entity.setRoleId(ao.getRoleId());
            entity.setPerId(item);

            saveEntity.add(entity);
        });

        boolean isSave = orgRolePermissionService.saveBatch(saveEntity);

        return JsonUtil.getResult(isSave);
    }


}
